package com.gzc.just.play.last.war.common.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 战斗会话管理器
 * 管理所有战斗会话的生命周期
 */
public class BattleSessionManager {
    private static final Logger logger = LoggerFactory.getLogger(BattleSessionManager.class);
    
    // 战斗ID到战斗会话的映射
    private final ConcurrentHashMap<Long, BattleSession> battleSessions = new ConcurrentHashMap<>();
    
    // 管理器状态
    private final AtomicBoolean running = new AtomicBoolean(false);
    
    // 单例实例
    private static volatile BattleSessionManager instance;
    
    /**
     * 获取战斗会话管理器单例
     */
    public static BattleSessionManager getInstance() {
        if (instance == null) {
            synchronized (BattleSessionManager.class) {
                if (instance == null) {
                    instance = new BattleSessionManager();
                }
            }
        }
        return instance;
    }
    
    /**
     * 私有构造函数
     */
    private BattleSessionManager() {
        logger.info("Created BattleSessionManager instance");
    }
    
    /**
     * 启动管理器
     */
    public void start() {
        if (running.compareAndSet(false, true)) {
            logger.info("Started BattleSessionManager");
        } else {
            logger.warn("BattleSessionManager is already running");
        }
    }
    
    /**
     * 停止管理器
     */
    public void stop() {
        if (running.compareAndSet(true, false)) {
            // 停止所有战斗会话
            stopAllBattles();
            logger.info("Stopped BattleSessionManager");
        } else {
            logger.warn("BattleSessionManager is already stopped");
        }
    }
    
    /**
     * 创建新的战斗会话
     * @param battleName 战斗名称
     * @return 战斗ID
     */
    public long createBattle(String battleName) {
        if (!running.get()) {
            logger.warn("BattleSessionManager is not running, cannot create battle");
            return -1;
        }
        
        BattleSession battleSession = BattleSession.createBattle(battleName);
        battleSession.start();
        
        battleSessions.put(battleSession.getBattleId(), battleSession);
        
        logger.info("Created new battle: {} ({})", battleSession.getBattleId(), battleName);
        return battleSession.getBattleId();
    }
    
    /**
     * 获取战斗会话
     * @param battleId 战斗ID
     * @return 战斗会话，如果不存在则返回null
     */
    public BattleSession getBattle(long battleId) {
        return battleSessions.get(battleId);
    }
    
    /**
     * 停止指定的战斗会话
     * @param battleId 战斗ID
     * @return 是否成功停止
     */
    public boolean stopBattle(long battleId) {
        BattleSession battleSession = battleSessions.get(battleId);
        if (battleSession != null) {
            battleSession.stop();
            battleSessions.remove(battleId);
            logger.info("Stopped battle: {}", battleId);
            return true;
        }
        return false;
    }
    
    /**
     * 停止所有战斗会话
     */
    public void stopAllBattles() {
        // 复制战斗ID列表，避免并发修改异常
        var battleIds = battleSessions.keySet().toArray(new Long[0]);
        
        for (Long battleId : battleIds) {
            stopBattle(battleId);
        }
        
        logger.info("Stopped all battles");
    }
    
    /**
     * 向指定战斗提交消息
     * @param battleId 战斗ID
     * @param playerId 玩家ID
     * @param messageId 消息ID
     * @param messageBytes 消息字节数组
     * @return 是否成功提交
     */
    public boolean submitMessage(long battleId, long playerId, int messageId, byte[] messageBytes) {
        BattleSession battleSession = battleSessions.get(battleId);
        if (battleSession != null) {
            return battleSession.submitMessage(playerId, messageId, messageBytes);
        }
        
        logger.warn("Battle {} not found, cannot submit message", battleId);
        return false;
    }
    
    /**
     * 获取当前活跃的战斗数量
     * @return 活跃战斗数量
     */
    public int getActiveBattleCount() {
        return battleSessions.size();
    }
    
    /**
     * 获取所有活跃战斗的ID集合
     * @return 活跃战斗ID集合
     */
    public java.util.Collection<Long> getAllActiveBattles() {
        return battleSessions.keySet();
    }
    
    /**
     * 检查指定战斗是否存在
     * @param battleId 战斗ID
     * @return 是否存在
     */
    public boolean hasBattle(long battleId) {
        return battleSessions.containsKey(battleId);
    }
    
    /**
     * 清理已结束的战斗会话
     */
    public void cleanupFinishedBattles() {
        // 复制战斗ID列表，避免并发修改异常
        var battleIds = battleSessions.keySet().toArray(new Long[0]);
        
        for (Long battleId : battleIds) {
            BattleSession battleSession = battleSessions.get(battleId);
            if (battleSession != null && !battleSession.isRunning()) {
                battleSessions.remove(battleId);
                logger.info("Cleaned up finished battle: {}", battleId);
            }
        }
    }
    
    /**
     * 获取管理器状态
     * @return 是否正在运行
     */
    public boolean isRunning() {
        return running.get();
    }
}